const express = require('express');
const app = express();
const cors = require('cors')
const http = require('http');
const server = http.createServer(app)
const { Server } = require("socket.io");
const io = new Server(server,{cors:true});
app.use(cors())

const users = [];  //所有用户
const onusers = [];//在线用户
const msglist = []; //消息列表

app.get('/',(req,res) => {
    res.send('<h1>Hello express</h1>')
});


io.on('connection', (socket) => {
    console.log('lj')
    //登陆
    socket.on('login',(data) => {
        //判断是否已经注册和登陆
        let user = users.find((item) => item.username === data.username)
        //已经注册
        if(user){
            //存在继续判断是否登陆了
            let onuser = onusers.find((item) => item.username === user.username)
            //已经登陆
            if(onuser){
                socket.emit('loginError',data)
            }else{
                onusers.push(user);
                socket.emit('loginSuccess',data)
                console.log('登陆成功')
                //在线列表
                io.emit( 'userlist',{msg:onusers})
                //在线人数
                io.emit('usernum',{msg:onusers.length})
                socket.username = data.username;
            }
        }else {
            users.push(data);
            onusers.push(data);
            socket.emit('loginSuccess',data)
            console.log('登陆成功')
            //在线列表
            io.emit( 'userlist',{msg:onusers})
            //在线人数
            io.emit('usernum',{msg:onusers.length})
            socket.username = data.username;
        }
    })

    //登出
    socket.on('disconnect',() => {
        let idx = onusers.findIndex((item) => item.username === socket.username)
        //将当前退出的用户从在线列表列表中删除
        onusers.splice(idx,1);
        //在线列表
        io.emit( 'userlist',{msg:onusers})
        //在线人数
        io.emit('usernum',{msg:onusers.length})
        console.log('dk')
    })

    //发送消息
    socket.on('send',(data) => {
        msglist.push(data)
        if(msglist.length > 50){
            msglist.pop()
        }
        io.emit('text',msglist)
    })
    io.emit('text',msglist)



});


server.listen(8080,() => {
    console.log('listening on * 8080');
})